const axios = require('axios')
const urlJoin = require('url-join')
const semver = require('semver')

async function fetchSemverVersions(originVersion, pkgName) {
  const versions = await fetchPkgVersions(pkgName)
  const newVersions = semverVersions(originVersion, versions)
  if (newVersions && newVersions.length > 0) {
    return newVersions[0]
  }
  return null
}

async function fetchLatestVersion(pkgName) {
  let versions = await fetchPkgVersions(pkgName)
  if (versions) {
    return semver.maxSatisfying(versions, '*')
  } else {
    return null
  }
}

function fetchPkgInfo(pkgName) {
  if (!pkgName) {
    return
  }
  const url = urlJoin('http://registry.npmjs.org', pkgName)
  return axios
    .get(url)
    .then(response => {
      if (response.status !== 200) {
        return
      }
      return response.data
    })
    .catch(err => {
      return Promise.reject(err)
    })
}

async function fetchPkgVersions(pkgName) {
  const data = await fetchPkgInfo(pkgName)
  return data ? Object.keys(data.versions) : []
}

// 获取所有满足条件的版本号
function semverVersions(originVersion, versions) {
  const result = versions
    .filter(
      version => semver.satisfies(version, `^${originVersion}`) // satisfies 过滤 >= 版本号
    )
    .sort((a, b) => (semver.gt(b, a) ? 1 : -1)) // 进行版本号排序，以防npmApi接口数据中版本号未排序
  return result
}

module.exports = {
  fetchSemverVersions,
  fetchLatestVersion,
}
